package com.sunday.volunteer.fragment.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.member.base.BaseFragment;
import com.sunday.member.common.MemberConst;
import com.sunday.member.utils.SharePerferenceUtils;
import com.sunday.volunteer.BaseApp;
import com.sunday.volunteer.R;
import com.sunday.volunteer.adapter.ActivityAdapter;
import com.sunday.volunteer.entity.Activity;
import com.sunday.volunteer.http.HttpClient;
import com.sunday.volunteer.utils.BaseUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Pual's PC on 2016/6/28.
 */
public class ActivityFragment extends BaseFragment {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.swipfresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.emptylayout)
    EmptyLayout emptyLayout;


    private int pageNo = 1;
    private boolean isCanloadMore = false;
    private LinearLayoutManager layoutManager;
    private ActivityAdapter adapter;
    private List<Activity> list;
    private int orderStatus;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_activity, null);
        ButterKnife.bind(this, rootView);
        orderStatus = getArguments().getInt("type");
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        list = new ArrayList<>();
        adapter = new ActivityAdapter(list ,R.layout.item_activity);
        adapter.setOnClickListener(onClickListener);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        swipeRefreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        recyclerView.setAdapter(adapter);

        getData();
        handlerRecyclerView();
    }

    private int lastVisibleItem;

    private void handlerRecyclerView() {
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                getData();
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        pageNo = 1;
                        getData();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    pageNo ++;
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                isCanloadMore = dy>0?true:false;
            }
        });
    }

    private void getData() {
        Call<ResultDO<List<Activity>>> call = HttpClient.getHttpAdapter().getMyActivitys(BaseApp.getInstance().getMemberId() , pageNo , 20 ,orderStatus, null);
        call.enqueue(new Callback<ResultDO<List<Activity>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Activity>>> call, Response<ResultDO<List<Activity>>> response) {
                swipeRefreshLayout.setRefreshing(false);
                if(response.body() == null || isFinish){
                    return;
                }
                if(response.body().getCode() == 0&& response.body().getResult() != null){
                    if(pageNo == 1){
                        list.clear();
                    }
                    list.addAll(response.body().getResult());
                    if(list.size() == 0){
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }else {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Activity>>> call, Throwable t) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void updata(){
        pageNo = 1;
        getData();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position  = (Integer)v.getTag();
            switch (v.getId()){
                case R.id.item:
                    BaseUtil.openActivityDetialActivity(mContext , list.get(position).getId());
                    break;
                //取消
                case R.id.btn:
                    updateOrder(position,"是否取消报名");
                    break;

            }
        }
    };

    private void updateOrder(final int position,String title){
        final UIAlertView uiAlertView = new UIAlertView(mContext , "温馨提示" , title  , "取消" , "确认");
        uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
            @Override
            public void doLeft() {
                uiAlertView.dismiss();
            }

            @Override
            public void doRight() {
                uiAlertView.dismiss();
                updateOrder(position);
            }
        });
        uiAlertView.show();
    }


    private void updateOrder(int position){
        Call<ResultDO> call = HttpClient.getHttpAdapter().quxiaobaoming(BaseApp.getInstance().getMemberId() , list.get(position).getId());

        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body().getCode() == 0 ) {
                        ToastUtils.showToast(mContext, "取消报名成功");
                    pageNo = 1;
                    getData();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_OK){
            updata();
        }
    }
}

